package com.krtech.wecard.framework.utils;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.ext.satoken.MySaTokenListener;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.enums.SysEnums;
import com.krtech.wecard.module.sys.mapper.SysUserMapper;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 登陆信息操作
 */
@Component
@Slf4j
public class LoginUtil {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysKeyValueService keyValueService;

    /**
     * 获得当前登陆用户信息
     *
     * @return
     */
//    public SysUser getUserInfo(){
//        long loginId = StpUtil.getLoginIdAsLong();
//        SysUser user = sysUserMapper.selectById(loginId);
//        return user;
//    }

    public static SysUser getUserInfo(){
        String tokenValue = StpUtil.getTokenInfo().getTokenValue();
        log.info("当前获得用户信息token:"+tokenValue);
        Long loginId = StpUtil.getLoginIdAsLong();
        String userStr = SaManager.getSaTokenDao().get("userInfo:" + loginId);
        SysUser user = JSONUtil.toBean(userStr, SysUser.class);
        log.info("当前获得用户信息user:"+JSONUtil.toJsonStr(user));
        return user;
    }

    public static SysUser getUserInfoByOAuth2Token(){
        String accessToken = StpUtil.getTokenValue();
        Object id = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
        String userStr = SaManager.getSaTokenDao().get("userInfo:" + id);
        SysUser user = JSONUtil.toBean(userStr, SysUser.class);
        return user;
    }

    public static SysUser getUserInfo(long loginId){
        String userStr = SaManager.getSaTokenDao().get("userInfo:" + loginId);
        SysUser user = JSONUtil.toBean(userStr, SysUser.class);
        return user;
    }

    /**
     * 判断当前用户是否是 超级管理员
     */
    public static boolean judgeAdmin(){
        List<String> roleList = StpUtil.getRoleList();
        String superAdmin = SaManager.getSaTokenDao().get("SUPER_ADMIN");
        return roleList.contains(superAdmin);
    }

}
